<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { grantRolesApi } from '#/api/system/account';
import { getRoleListApi } from '#/api/system/role';

defineOptions({
  name: 'UserRoleFormModal',
});

const emit = defineEmits<{
  complete: [];
}>();

async function onSubmit(values: Record<string, any>) {
  await grantRolesApi(values.userId, values.roleIds);
  message.success('授权成功');
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 60,
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        mode: 'multiple',
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
      fieldName: 'roleIds',
      label: '角色',
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      modalApi.close();
      emit('complete');
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { userId, realname, roleIds } =
        modalApi.getData<Record<string, any>>();
      formApi.setValues({ userId, roleIds }, false);
      modalApi.setState({ title: `分配角色 (${realname})` });

      const roles = await getRoleListApi();
      formApi.updateSchema([
        {
          componentProps: {
            options: roles,
          },
          fieldName: 'roleIds',
        },
      ]);
    }
  },
  title: '分配角色',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
